import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Switch, Statistic, Table, Tag, Progress, Space, Typography, message, Button } from 'antd';
import {
  ClockCircleOutlined,
  CarOutlined,
  ExclamationCircleOutlined,
  UserOutlined,
  VideoCameraOutlined,
  UpOutlined,
  DownOutlined
} from '@ant-design/icons';
import {
  getElevatorInfo,
  getOperationData,
  getRealTimeData,
  getAlarmRecords,
  getAlarmSummary,
  type ElevatorInfo,
  type OperationData,
  type RealTimeData,
  type AlarmRecord
} from '../../services/elevator';
import './index.less';

const { Title, Text } = Typography;

const ElevatorMonitor: React.FC = () => {
  const [isRealTimeEnabled, setIsRealTimeEnabled] = useState(false);
  const [isTodayData, setIsTodayData] = useState(true);
  const [currentTime, setCurrentTime] = useState(new Date());

  // 数据状态
  const [operationData, setOperationData] = useState<OperationData | null>(null);
  const [realTimeData, setRealTimeData] = useState<RealTimeData | null>(null);
  const [alarmRecords, setAlarmRecords] = useState<AlarmRecord[]>([]);
  const [alarmSummary, setAlarmSummary] = useState({ total: 0, processed: 0 });
  const [loading, setLoading] = useState(true);
  const [currentAlarmIndex, setCurrentAlarmIndex] = useState(0);

  // 固定的电梯信息
  const elevatorInfo: ElevatorInfo = {
    productName: 'KONE E MonoSpace® DX 无机房乘客电梯',
    model: 'KONE MonoSpace / PW10/10-19',
    location: '江苏省/南京市/建邺区/南苑街道',
    ratedLoad: 800,
    ratedSpeed: 1.0,
    floors: 10
  };

  // 告警记录表格列配置
  const alarmColumns = [
    {
      title: '故障时间',
      dataIndex: 'faultTime',
      key: 'faultTime',
      width: 120,
    },
    {
      title: '故障名称',
      dataIndex: 'faultName',
      key: 'faultName',
      width: 120,
    },
    {
      title: '故障楼层',
      dataIndex: 'faultFloor',
      key: 'faultFloor',
      width: 100,
      render: (floor: number) => `${floor}层`,
    },
    {
      title: '故障状态',
      dataIndex: 'faultStatus',
      key: 'faultStatus',
      width: 100,
      render: (status: string) => (
        <Tag color={status === 'pending' ? 'orange' : 'green'}>
          {status === 'pending' ? '待处理' : '已处理'}
        </Tag>
      ),
    },
  ];

  // 初始化数据加载
  useEffect(() => {
    const loadInitialData = async () => {
      try {
        setLoading(true);
        const [operation, records, summary] = await Promise.all([
          getOperationData(isTodayData),
          getAlarmRecords(),
          getAlarmSummary()
        ]);

        setOperationData(operation);
        setAlarmRecords(records);
        setAlarmSummary(summary);
      } catch (error) {
        message.error('数据加载失败');
        console.error('数据加载失败:', error);
      } finally {
        setLoading(false);
      }
    };

    loadInitialData();
  }, [isTodayData]);

  // 更新时间
  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentTime(new Date());
    }, 1000);

    return () => clearInterval(timer);
  }, []);

  // 实时数据更新
  useEffect(() => {
    if (!isRealTimeEnabled) return;

    const realTimeTimer = setInterval(async () => {
      try {
        const data = await getRealTimeData();
        setRealTimeData(data);
      } catch (error) {
        console.error('实时数据获取失败:', error);
      }
    }, 3000);

    return () => clearInterval(realTimeTimer);
  }, [isRealTimeEnabled]);

  const formatTime = (date: Date) => {
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    const weekday = weekdays[date.getDay()];
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');

    return `${hours}:${minutes}:${seconds} ${weekday} ${year}.${month}.${day}`;
  };

  const getDirectionIcon = (direction: string) => {
    switch (direction) {
      case 'up':
        return <UpOutlined style={{ color: '#52c41a' }} />;
      case 'down':
        return <DownOutlined style={{ color: '#ff4d4f' }} />;
      default:
        return null;
    }
  };

  // 自动滚动效果 - 告警记录滚动
  useEffect(() => {
    if (alarmRecords.length === 0) return;

    const tableBody = document.querySelector('.alarm-records-card .ant-table-body');
    if (!tableBody) return;

    let scrollTop = 0;
    const scrollHeight = tableBody.scrollHeight - tableBody.clientHeight;
    const scrollStep = 1; // 每次滚动的像素

    const interval = setInterval(() => {
      scrollTop += scrollStep;
      if (scrollTop >= scrollHeight) {
        scrollTop = 0; // 回到顶部
      }
      tableBody.scrollTop = scrollTop;
    }, 50); // 每50ms滚动一次，实现平滑滚动

    return () => clearInterval(interval);
  }, [alarmRecords.length]);



  return (
    <div className="elevator-monitor">
      {/* 头部时间显示 */}
      <div className="monitor-header">
        <Title level={2} className="monitor-title">梯联网大数据监控中心</Title>
        <div className="current-time">
          <ClockCircleOutlined />
          <Text>{formatTime(currentTime)}</Text>
        </div>
      </div>

      <Row gutter={[16, 16]} className="monitor-content">
        {/* 左侧面板 - 电梯信息和运行数据 */}
        <Col span={8}>
          <Card title="电梯信息" className="info-card">
            <div className="info-item">
              <Text className='info-text' strong>产品名称：</Text>
              <Text>{elevatorInfo.productName}</Text>
            </div>
            <div className="info-item">
              <Text className='info-text' strong>型号/规格：</Text>
              <Text>{elevatorInfo.model}</Text>
            </div>
            <div className="info-item">
              <Text className='info-text' strong>行政区划：</Text>
              <Text>{elevatorInfo.location}</Text>
            </div>
            <div className="info-item">
              <Text className='info-text' strong>额定载重量：</Text>
              <Text>{elevatorInfo.ratedLoad} 公斤</Text>
            </div>
            <div className="info-item">
              <Text className='info-text' strong>额定速度：</Text>
              <Text>{elevatorInfo.ratedSpeed} 米/秒</Text>
            </div>
            <div className="info-item">
              <Text className='info-text' strong>物理层数：</Text>
              <Text>{elevatorInfo.floors} 层</Text>
            </div>
          </Card>

          <Card title="运行数据" className="operation-card" loading={loading}>
            <div className="data-toggle">
              <Button.Group>
                <Button
                  type={isTodayData ? 'primary' : 'default'}
                  onClick={() => setIsTodayData(true)}
                  style={{
                    backgroundColor: isTodayData ? '#1890ff' : 'rgba(24, 144, 255, 0.3)',
                    borderColor: '#1890ff',
                    color: isTodayData ? '#fff' : '#1890ff'
                  }}
                >
                  今日
                </Button>
                <Button
                  type={!isTodayData ? 'primary' : 'default'}
                  onClick={() => setIsTodayData(false)}
                  style={{
                    backgroundColor: !isTodayData ? '#1890ff' : 'rgba(24, 144, 255, 0.3)',
                    borderColor: '#1890ff',
                    color: !isTodayData ? '#fff' : '#1890ff'
                  }}
                >
                  累计
                </Button>
              </Button.Group>
            </div>
            {operationData && (
              <Row gutter={[16, 16]}>
                <Col span={12}>
                  <Statistic className='operation-statistic' title="运行次数" value={operationData.runCount} suffix="次" />
                </Col>
                <Col span={12}>
                  <Statistic className='operation-statistic' title="运行时长" value={operationData.runTime} suffix="小时" />
                </Col>
                <Col span={12}>
                  <Statistic className='operation-statistic' title="运行距离" value={operationData.runDistance} suffix="米" />
                </Col>
                <Col span={12}>
                  <Statistic className='operation-statistic' title="停梯次数" value={operationData.stopCount} suffix="次" />
                </Col>
                <Col span={12}>
                  <Statistic className='operation-statistic' title="停梯时长" value={operationData.stopTime} suffix="小时" />
                </Col>
                <Col span={12}>
                  <Statistic className='operation-statistic' title="开关门次数" value={operationData.doorCount} suffix="次" />
                </Col>
              </Row>
            )}
          </Card>

          <Card title="实时数据" className="realtime-card">
            <div className="realtime-toggle">
              <Switch
                checked={isRealTimeEnabled}
                onChange={setIsRealTimeEnabled}
                checkedChildren="开启"
                unCheckedChildren="关闭"
              />
              <Text type="secondary">开启后实时查询数据</Text>
            </div>
            {realTimeData ? (
              <div className="realtime-info">
                <div className="info-item">
                  <Text strong>更新时间：</Text>
                  <Text>{realTimeData.updateTime}</Text>
                </div>
                <div className="info-item">
                  <Text strong>当前楼层：</Text>
                  <Text>{realTimeData.currentFloor.toString().padStart(2, '0')} 层</Text>
                </div>
                <div className="info-item">
                  <Text strong>运行方向：</Text>
                  <Space>
                    {getDirectionIcon(realTimeData.direction)}
                    <Text>{realTimeData.direction === 'up' ? '上行' : realTimeData.direction === 'down' ? '下行' : '待机'}</Text>
                  </Space>
                </div>
                <div className="info-item">
                  <Text strong>梯门状态：</Text>
                  <Text>{realTimeData.doorStatus === 'open' ? '开启' : '关闭'}</Text>
                </div>
                <div className="info-item">
                  <Text strong>实时载重：</Text>
                  <Progress percent={realTimeData.load} size="small" />
                </div>
                <div className="info-item">
                  <Text strong>当前速度：</Text>
                  <Text>{realTimeData.speed} m/秒</Text>
                </div>
                <div className="info-item">
                  <Text strong>运行模式：</Text>
                  <Text>{realTimeData.mode}</Text>
                </div>
              </div>
            ) : (
              <div className="realtime-info">
                <Text type="secondary">请开启实时数据开关查看实时信息</Text>
              </div>
            )}
          </Card>
        </Col>

        {/* 中间面板 - 电梯位置和可视化 */}
        <Col span={8}>
          <Card title="电梯位置" className="location-card">
            <div className="elevator-location">
              <Title level={4}>江南名府11栋2单元</Title>
            </div>
            <div className="elevator-visualization">
              <div className="elevator-shaft">
                {/* 电梯井楼层指示 */}
                {Array.from({ length: 10 }, (_, i) => (
                  <div key={i} className="floor-indicator">
                    <span className="floor-number">{10 - i}</span>
                  </div>
                ))}
                {/* 电梯轿厢 */}
                <div
                  className="elevator-car"
                  style={{
                    bottom: `${(realTimeData?.currentFloor || 7) * 10}%`,
                    transform: `translateY(${realTimeData?.direction === 'up' ? '-5px' : realTimeData?.direction === 'down' ? '5px' : '0'})`
                  }}
                >
                  <div className="car-body">
                    <div className="car-label">张梦姿</div>
                    <div className="car-status">
                      {realTimeData?.direction === 'up' && <UpOutlined className="direction-icon up" />}
                      {realTimeData?.direction === 'down' && <DownOutlined className="direction-icon down" />}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </Card>
        </Col>

        {/* 右侧面板 - 视频和告警 */}
        <Col span={8}>
          <Card title="轿厢实时画面" className="video-card">
            <div className="video-container">
              <div className="video-placeholder">
                <div className="video-timestamp">2023-07-17 11:30:00</div>
                <div className="video-content">
                  <div className="video-background">
                    <div className="person-detection">
                      <div className="person-box person-1">
                        <div className="face-label">人脸识别</div>
                      </div>
                      <div className="person-box person-2">
                        <div className="face-label">人脸识别</div>
                      </div>
                      <div className="person-box person-3">
                        <div className="face-label">人脸识别</div>
                      </div>
                    </div>
                  </div>
                  <div className="video-info">
                    <Text className="info-text">人脸识别</Text>
                    <Text className="info-text">人数：3</Text>
                  </div>
                </div>
              </div>
            </div>
          </Card>

          <Card title="累计异常告警" className="alarm-summary-card" loading={loading}>
            <Row gutter={16}>
              <Col span={12}>
                <Statistic
                  title="累计告警"
                  value={alarmSummary.total}
                  suffix="次"
                  prefix={<ExclamationCircleOutlined style={{ color: '#ff4d4f' }} />}
                />
              </Col>
              <Col span={12}>
                <Statistic
                  title="已处理"
                  value={alarmSummary.processed}
                  suffix="次"
                  prefix={<UserOutlined style={{ color: '#52c41a' }} />}
                />
              </Col>
            </Row>
          </Card>

          <Card title="异常告警记录" className="alarm-records-card" loading={loading}>
            <Table
              columns={alarmColumns}
              dataSource={alarmRecords}
              pagination={false}
              size="small"
              scroll={{ y: 150 }}
              rowKey={(record, index) => `alarm-${index}`}
              className="alarm-table"
            />
          </Card>
        </Col>
      </Row>

      {/* 底部实时状态栏 */}
      <div className="status-bar">
        <div className="status-item">
          <Text className='status-text' strong>更新时间：</Text>
          <Text>{realTimeData?.updateTime || '--'}</Text>
        </div>
        <div className="status-item">
          <Text className='status-text' strong>当前楼层：</Text>
          <Text>{realTimeData?.currentFloor ? `${realTimeData.currentFloor.toString().padStart(2, '0')} 层` : '--'}</Text>
        </div>
        <div className="status-item">
          <Text className='status-text' strong>运行方向：</Text>
          <Space>
            {realTimeData && getDirectionIcon(realTimeData.direction)}
            <Text>{realTimeData?.direction === 'up' ? '上行' : realTimeData?.direction === 'down' ? '下行' : '待机'}</Text>
          </Space>
        </div>
        <div className="status-item">
          <Text className='status-text' strong>梯门状态：</Text>
          <Text>{realTimeData?.doorStatus === 'open' ? '开启' : realTimeData?.doorStatus === 'closed' ? '关闭' : '--'}</Text>
        </div>
        <div className="status-item">
          <Text className='status-text' strong>实时载重：</Text>
          <Text>{realTimeData?.load ? `${realTimeData.load}%` : '--'}</Text>
        </div>
        <div className="status-item">
          <Text className='status-text' strong>当前速度：</Text>
          <Text>{realTimeData?.speed ? `${realTimeData.speed} m/秒` : '--'}</Text>
        </div>
        <div className="status-item">
          <Text strong>运行模式：</Text>
          <Text>{realTimeData?.mode || '--'}</Text>
        </div>
      </div>
    </div>
  );
};

export default ElevatorMonitor; 